using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace Lab5DeferredShading
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        private GraphicsDeviceManager m_graphics;
        private SpriteBatch m_spriteBatch;

        private Effect m_effects;
        private Effect m_DrawEffect;
        private Model m_modelToDraw;

        private VertexBuffer m_vertexBuffer;
        private IndexBuffer m_indexBuffer;

        private readonly Vector3 CameraPosition = new Vector3(0.0f, 0.0f, 0.0f);
        private const double FieldOfView = 70.0;

        private RenderTargetBinding[] m_GBufferTargets = new RenderTargetBinding[3];

        public Game1()
        {
            m_graphics = new GraphicsDeviceManager(this);
            m_graphics.PreferredBackBufferWidth = 1024;
            m_graphics.PreferredBackBufferHeight = 1024;
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // SpriteBatch
            m_spriteBatch = new SpriteBatch(m_graphics.GraphicsDevice);

            // Load the effect.
            m_effects = Content.Load<Effect>("Effects/Effect1");
            m_DrawEffect = Content.Load<Effect>("Effects/DrawToScreen");

            // Load the Model.
            m_modelToDraw = Content.Load<Model>("Models/Sphere");

            // Remap Models.
            RemapModel(m_modelToDraw, m_effects);

            // Set the technique
            m_effects.CurrentTechnique = m_effects.Techniques["Deferred"];
            m_DrawEffect.CurrentTechnique = m_DrawEffect.Techniques["Technique1"];



            // Create the Vertex buffer.
            m_vertexBuffer = new VertexBuffer(m_graphics.GraphicsDevice, typeof(VertexPositionNormalTexture), 6, BufferUsage.None);
            VertexPositionNormalTexture[] vdata = new VertexPositionNormalTexture[4];

            vdata[0].Position = new Vector3(-1.0f, -1.0f, 0.0f);
            vdata[0].Normal = new Vector3(0.0f, 0.0f, 1.0f);
            vdata[0].TextureCoordinate = new Vector2(0.0f, 1.0f);

            vdata[1].Position = new Vector3(-1.0f, 1.0f, 0.0f);
            vdata[1].Normal = new Vector3(0.0f, 0.0f, 1.0f);
            vdata[1].TextureCoordinate = new Vector2(0.0f, 0.0f);

            vdata[2].Position = new Vector3(1.0f, 1.0f, 0.0f);
            vdata[2].Normal = new Vector3(0.0f, 0.0f, 1.0f);
            vdata[2].TextureCoordinate = new Vector2(1.0f, 0.0f);

            vdata[3].Position = new Vector3(1.0f, -1.0f, 0.0f);
            vdata[3].Normal = new Vector3(0.0f, 0.0f, 1.0f);
            vdata[3].TextureCoordinate = new Vector2(1.0f, 1.0f);

            m_vertexBuffer.SetData<VertexPositionNormalTexture>(vdata);

            // Create the index buffer.
            short[] indexList = new short[6] { 0, 1, 2, 0, 2, 3 };
            m_indexBuffer = new IndexBuffer(m_graphics.GraphicsDevice, IndexElementSize.SixteenBits, 6, BufferUsage.None);
            m_indexBuffer.SetData<short>(indexList);

            // Create the gbuffer.
            int width = 1024;
            int height = 1024;

            Vector2 GBufferTextureSize = new Vector2(width, height);

            m_GBufferTargets[0] = new RenderTargetBinding(new RenderTarget2D(m_graphics.GraphicsDevice, width, height, false, SurfaceFormat.Rgba64, DepthFormat.Depth24Stencil8));
            m_GBufferTargets[1] = new RenderTargetBinding(new RenderTarget2D(m_graphics.GraphicsDevice, width, height, false, SurfaceFormat.Rgba64, DepthFormat.Depth24Stencil8));
            m_GBufferTargets[2] = new RenderTargetBinding(new RenderTarget2D(m_graphics.GraphicsDevice, width, height, false, SurfaceFormat.Rgba64, DepthFormat.Depth24Stencil8));
        }

        private static void RemapModel(Model a_model, Effect a_effect)
        {
            foreach (ModelMesh mesh in a_model.Meshes)
            {
                foreach (ModelMeshPart part in mesh.MeshParts)
                {
                    part.Effect = a_effect;
                }
            }
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape) == true)
                this.Exit();

            // TODO: Add your update logic here

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Transparent);

            // Set the render target.
            m_graphics.GraphicsDevice.SetRenderTargets(m_GBufferTargets);

            GraphicsDevice.Clear(Color.Transparent);

            float aspectRatio = m_graphics.GraphicsDevice.Viewport.AspectRatio;

            Matrix world = Matrix.CreateTranslation(0.0f, 0.0f, 0.0f) * Matrix.CreateScale(15.0f);
            Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians((float)FieldOfView), aspectRatio, 10.0f, 1000.0f);
            Matrix view = Matrix.CreateLookAt(new Vector3(0.0f, 0.0f, 100.0f), Vector3.Zero, Vector3.Up);

            foreach (ModelMesh mesh in m_modelToDraw.Meshes)
            {
                foreach (Effect e in mesh.Effects)
                {
                    e.Parameters["Projection"].SetValue(projection);
                    e.Parameters["View"].SetValue(view);
                    e.Parameters["World"].SetValue(world);
                }
                mesh.Draw();
            }

            // Reset the render target.
            m_graphics.GraphicsDevice.SetRenderTargets(null);

            DrawToScreen(new Vector3(20.0f, 5.0f, 30.0f));

            DrawBuffer();

            base.Draw(gameTime);
        }

        private void DrawBuffer()
        {
            int width = 128;
            int height = 128;

            m_spriteBatch.Begin(0, BlendState.Opaque, SamplerState.PointClamp, DepthStencilState.Default, null);
            m_spriteBatch.Draw((Texture2D)m_GBufferTargets[0].RenderTarget, new Rectangle(0, 0, width, height), Color.White);
            m_spriteBatch.Draw((Texture2D)m_GBufferTargets[1].RenderTarget, new Rectangle(width, 0, width, height), Color.White);
            m_spriteBatch.Draw((Texture2D)m_GBufferTargets[2].RenderTarget, new Rectangle(width * 2, 0, width, height), Color.White);
            m_spriteBatch.End();
        }

        private void DrawToScreen(Vector3 a_lightPos)
        {
            m_graphics.GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Green, 1.0f, 0);

            m_DrawEffect.Parameters["World"].SetValue(Matrix.Identity);
            m_DrawEffect.Parameters["View"].SetValue(Matrix.CreateTranslation(new Vector3(0.0f, 0.0f, 1.0f)));
            m_DrawEffect.Parameters["Projection"].SetValue(Matrix.Identity);

            m_DrawEffect.Parameters["WorldPosMap"].SetValue(m_GBufferTargets[0].RenderTarget);
            m_DrawEffect.Parameters["TextureMap"].SetValue(m_GBufferTargets[1].RenderTarget);
            m_DrawEffect.Parameters["NormalMap"].SetValue(m_GBufferTargets[2].RenderTarget);
            m_DrawEffect.Parameters["LightPos"].SetValue(a_lightPos);

            m_graphics.GraphicsDevice.SetVertexBuffer(m_vertexBuffer);
            m_graphics.GraphicsDevice.Indices = m_indexBuffer;

            foreach (EffectPass pass in m_DrawEffect.CurrentTechnique.Passes)
            {
                pass.Apply();
                m_graphics.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 4, 0, 2);
            }
        }
    }
}